//
//  SN_SearchViewController.m
//  Shiyun_Newspaper
//
//  Created by Sylar on 2017/6/16.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#import "SN_SearchViewController.h"
#import "SNSearchBar.h"
#import "SN_SearchResultCell.h"
#import "SN_NewspaperInfoViewController.h"
#import "SN_Question_ResolveController.h"

@interface SN_SearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSString *defaultGrader;
    NSString *defaultEdition;
    
    NSInteger defaultSelectedEditionIndex;
    
    NSInteger selectedEditionIndex;
    NSInteger selectedGradeIndex;
    
    NSInteger pageNum;
}

@property (nonatomic, strong) SNSearchBar *snSearch;
@property (nonatomic, strong) UIButton *subjectBtn;
@property (nonatomic, strong) UIButton *scanBtn;
@property (nonatomic, strong) UIControl *control;

@property (nonatomic, strong)UITableView *sel_edition;
@property (nonatomic, strong)UITableView *sel_grader;

@property (nonatomic, strong) UITableView *resultTable;
@property (nonatomic, strong) UILabel *noResultLabel;

@property (nonatomic, strong) NSMutableArray *graderArr;
@property (nonatomic, strong) NSMutableArray *editionArr;
@property (nonatomic, strong) NSMutableArray *resultArr;

@end

@implementation SN_SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    selectedEditionIndex = 0;
    defaultSelectedEditionIndex = 0;
    defaultGrader = self.gradersName;
    defaultEdition = self.editionName;
    
    pageNum = 1;
    
    self.navBar.navigationItem.leftBarButtonItem = nil;
    
    [self layoutView];
    
    [[DBUtil shareInstance] getEditionAndGradeData:^(NSError *error, NSDictionary *editionInfo, NSDictionary *gradeInfo) {
        
        self.graderArr = [gradeInfo objectForKey:@"re_data"];
        self.editionArr = [editionInfo objectForKey:@"re_data"];
        
        for (int i = 0; i < self.editionArr.count; i++) {
            
            if ([self.editionName isEqualToString:[[self.editionArr objectAtIndex:i] objectForKey:@"editiontypename"]]) {
                defaultSelectedEditionIndex = i;
                selectedEditionIndex = i;
                break;
            }
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)dealloc {
    
}

#pragma mark - Method

- (void)layoutView {
    
    NSString *subStr = [NSString stringWithFormat:@"%@ · %@",self.editionName,self.gradersName];
    
    self.subjectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.subjectBtn addTarget:self action:@selector(selectSubject) forControlEvents:(UIControlEventTouchUpInside)];
    [self.subjectBtn setFrame:CGRectMake(15, SafeAreaTopHeight - 18-13, 134, 18)];
    self.subjectBtn.adjustsImageWhenHighlighted = NO;
    [self.subjectBtn setTitle:subStr forState:(UIControlStateNormal)];
    [self.subjectBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [self.subjectBtn setTitleColor:colorFromHex(@"#ffffff") forState:UIControlStateNormal];
    [self.subjectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -40, 0, 0)];
    [self.subjectBtn setImage:[UIImage imageNamed:@"choose_Down"] forState:(UIControlStateNormal)];
    [self.subjectBtn setImage:[UIImage imageNamed:@"choose_Up"] forState:(UIControlStateSelected)];
    [self.subjectBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 112, 0, 0)];
    [self.navBar addSubview:self.subjectBtn];
    
    self.snSearch = [[SNSearchBar alloc]initWithFrame:CGRectMake(self.subjectBtn.right, SafeAreaTopHeight - 28 -8, SCREENWIDTH-30-15-35-self.subjectBtn.width, 28) leftImage:[UIImage imageNamed:@"search_Img"] placeholderColor:colorFromHex(@"#bebebe")];
    self.snSearch.hasCentredPlaceholder = NO;
    self.snSearch.delegate = self;
    self.snSearch.layer.cornerRadius = 4;
    self.snSearch.layer.masksToBounds = YES;
    [self.snSearch setPlaceholder:@"搜索"];
    [self.snSearch setBackgroundColor:[UIColor whiteColor]];
    [self.snSearch setBackgroundImage:[Utils imageWithColor:[UIColor clearColor] size:self.snSearch.bounds.size]];
    [self.navBar addSubview:self.snSearch];
    
    [self.snSearch becomeFirstResponder];
    
    [self.view addSubview:self.resultTable];
    
    UIButton *cancleBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [cancleBtn setFrame:CGRectMake(self.snSearch.right+15, SafeAreaTopHeight - 28-8, 35, 28)];
    [cancleBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [cancleBtn setTitle:@"取消" forState:(UIControlStateNormal)];
    [cancleBtn setTitleColor:colorFromHex(@"ffffff") forState:(UIControlStateNormal)];
    [cancleBtn addTarget:self action:@selector(popVC) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.navBar addSubview:cancleBtn];
    
    self.noResultLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight+200, SCREENWIDTH, 14)];
    [self.noResultLabel setTextColor:colorFromHex(@"979797")];
    [self.noResultLabel setFont:[UIFont systemFontOfSize:14]];
    [self.noResultLabel setTextAlignment:NSTextAlignmentCenter];
    [self.noResultLabel setHidden:YES];
    [self.noResultLabel setText:@"搜索结果为空，请试试其他关键词吧"];
    [self.view addSubview:self.noResultLabel];
    
}

- (void)popVC {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)selectSubject {
    
    [self.snSearch resignFirstResponder];
    self.subjectBtn.selected = !self.subjectBtn.selected;
    
    if (_control) {
        [self hideControl];
    }else {
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(SCREENWIDTH/2-0.5, 40*self.editionArr.count, 0.5, 40*(9-self.editionArr.count))];
        [line setBackgroundColor:colorFromHex(@"#DEDEDE")];
        [self.sel_edition addSubview:line];
        [self.control addSubview:self.sel_edition];
        [self.control addSubview:self.sel_grader];
        
        [self.view addSubview:self.control];
    }
}

- (void)hideControl {
    
    self.subjectBtn.selected = NO;
    [self.control removeFromSuperview];
    self.control = nil;
    
    self.sel_grader = nil;
    self.sel_edition = nil;
    
    defaultGrader = self.gradersName;
    defaultEdition = self.editionName;
    
    defaultSelectedEditionIndex = selectedEditionIndex;
}

#pragma mark - SearchDelegate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    if (searchText.length > 0) {
        [self searchRequest:searchText];
    }else {
        self.resultArr = [[NSMutableArray alloc]init];
        
        self.noResultLabel.hidden = self.resultArr.count == 0 ?NO:YES;
        [self.resultTable reloadData];
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

    if (searchBar.text.length > 0) {
        [self searchRequest:searchBar.text];
    }
    
}

#pragma mark - Request

- (void)searchRequest:(NSString *)searchText {
    
    if (searchText.length == 0 ) {
        
        [self.resultTable.mj_header endRefreshing];
        return;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.operationQueue cancelAllOperations];
    
    NSMutableDictionary *paramDic = [[NSMutableDictionary alloc]init];
    
    [paramDic setObject:self.searchType == 0?@"api_szb_searchlist":@"api_szb_searchquestionlist" forKey:@"method"];
    [paramDic setObject:searchText forKey:@"scontent"];
    [paramDic setObject:@"1" forKey:@"pageno"];
    [paramDic setObject:@"20" forKey:@"pagesize"];
    [paramDic setObject:self.editionType forKey:@"editiontype"];
    [paramDic setObject:self.gradersId forKey:@"gradersid"];
    
    [Utils getWithparameters:paramDic showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *re_data = (NSDictionary *)jsonObject;
        
        NSArray *arr = [re_data objectForKey:@"re_data"];
        
        self.resultArr = [[NSMutableArray alloc]init];
        
        for (NSDictionary *dic in arr) {
            
            SN_NewspaperModel *model = [SN_NewspaperModel mj_objectWithKeyValues:dic];
            [self.resultArr addObject:model];
        }
        
        self.noResultLabel.hidden = self.resultArr.count == 0 ?NO:YES;
        [self.resultTable reloadData];
        [self.resultTable.mj_header endRefreshing];
        
    } failure:^(NSInteger recode, NSError *error) {
        [self.resultTable.mj_header endRefreshing];
        
    }];
}

- (void)loadMoreResult:(NSString *)searchText {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.operationQueue cancelAllOperations];
    
    pageNum += 1;
    
    NSMutableDictionary *paramDic = [[NSMutableDictionary alloc]init];
    
    [paramDic setObject:self.searchType == 0?@"api_szb_searchlist":@"api_szb_searchquestionlist" forKey:@"method"];
    [paramDic setObject:searchText forKey:@"scontent"];
    [paramDic setObject:[NSString stringWithFormat:@"%ld",pageNum] forKey:@"pageno"];
    [paramDic setObject:@"20" forKey:@"pagesize"];
    [paramDic setObject:self.editionType forKey:@"editiontype"];
    [paramDic setObject:self.gradersId forKey:@"gradersid"];
    
    [Utils getWithparameters:paramDic showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *re_data = (NSDictionary *)jsonObject;
        
        NSArray *arr = [re_data objectForKey:@"re_data"];
        
        if (arr.count == 20) {
            for (NSDictionary *dic in arr) {
                
                SN_NewspaperModel *model = [SN_NewspaperModel mj_objectWithKeyValues:dic];
                [self.resultArr addObject:model];
            }
            
            self.noResultLabel.hidden = self.resultArr.count == 0 ?NO:YES;
            [self.resultTable reloadData];
            [self.resultTable.mj_footer endRefreshing];
        }else if ( 20 > arr.count > 0){
            
            for (NSDictionary *dic in arr) {
                
                SN_NewspaperModel *model = [SN_NewspaperModel mj_objectWithKeyValues:dic];
                [self.resultArr addObject:model];
            }
            
            self.noResultLabel.hidden = self.resultArr.count == 0 ?NO:YES;
            [self.resultTable reloadData];
            [self.resultTable.mj_footer endRefreshingWithNoMoreData];
            
        }else if (arr.count == 0) {
            [self.resultTable.mj_footer endRefreshingWithNoMoreData];
            pageNum -= 1;
        }
        
        
    } failure:^(NSInteger recode, NSError *error) {
        [self.resultTable.mj_footer endRefreshing];
        pageNum -= 1;
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.sel_grader) {
        return self.graderArr.count;
    }else if (tableView == self.sel_edition) {
        return self.editionArr.count;
    }else if (tableView == self.resultTable) {
        return self.resultArr.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.resultTable) {
        
    
    SN_SearchResultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    
    if (cell == nil) {
        cell = [[SN_SearchResultCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellIdentifier"];
    }
    
    SN_NewspaperModel *model = [self.resultArr objectAtIndex:indexPath.row];
    
    [cell creatCell:model type:self.searchType searchContent:self.snSearch.text];
    
    
    return cell;
    } else if (tableView == self.sel_edition) {
        
        UITableViewCell *editionCell = [tableView dequeueReusableCellWithIdentifier:@"editionIdentifier"];
        
        if (editionCell == nil) {
            editionCell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"editionIdentifier"];
            
            editionCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        for (UIView *view in editionCell.contentView.subviews) {
            if (view.tag > 60) {
                [view removeFromSuperview];
            }
        }
        
        NSDictionary *dict = [self.editionArr objectAtIndex:indexPath.row];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH/2, 40)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.tag = 61;
        [titleLabel setTextColor:colorFromHex(@"#3b3b3b")];
        [titleLabel setFont:[UIFont systemFontOfSize:16]];
        [titleLabel setText:[dict objectForKey:@"editiontypename"]];
        [editionCell.contentView addSubview:titleLabel];
        
        if ([[dict objectForKey:@"editiontypename"] isEqualToString:defaultEdition]) {
            [titleLabel setTextColor:colorFromHex(@"#fb524a")];
            [editionCell setBackgroundColor:[UIColor whiteColor]];
        }else {
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(SCREENWIDTH/2-0.5, 0, 0.5, 40)];
            [line setBackgroundColor:colorFromHex(@"#dedede")];
            line.tag = 62;
            [editionCell.contentView addSubview:line];
            [editionCell setBackgroundColor:colorFromHex(@"#f4f5f7")];
        }
        
        return editionCell;
        
    }else if (tableView == self.sel_grader) {
        
        UITableViewCell *graderCell = [tableView dequeueReusableCellWithIdentifier:@"graderIdentifier"];
        
        if (graderCell == nil) {
            graderCell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"graderIdentifier"];
            graderCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        for (UIView *view in graderCell.contentView.subviews) {
            if (view.tag > 50) {
                [view removeFromSuperview];
            }
        }
        
        NSDictionary *dict = [self.graderArr objectAtIndex:indexPath.row];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH/2, 40)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.tag = 60;
        if ([[dict objectForKey:@"gradername"] isEqualToString:defaultGrader]) {
            [titleLabel setTextColor:colorFromHex(@"#fb524a")];
        }else {
            [titleLabel setTextColor:colorFromHex(@"#3b3b3b")];
        }
        
        if (defaultGrader == nil && indexPath.row == 0) {
            [titleLabel setTextColor:colorFromHex(@"#fb524a")];
        }
        
        [titleLabel setFont:[UIFont systemFontOfSize:16]];
        [titleLabel setText:[dict objectForKey:@"gradername"]];
        
        [graderCell.contentView addSubview:titleLabel];
        
        return graderCell;
    }
    
    return nil;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.sel_edition) {
        
        if (defaultSelectedEditionIndex != indexPath.row) {
            defaultGrader = nil;
            [self.sel_grader reloadData];
        }
        defaultSelectedEditionIndex = indexPath.row;
        defaultEdition = [[self.editionArr objectAtIndex:indexPath.row] objectForKey:@"editiontypename"];;
        
        [self.sel_edition reloadData];
        
        
    }else if (tableView == self.sel_grader) {
        
        selectedEditionIndex = defaultSelectedEditionIndex;
        selectedGradeIndex = indexPath.row;
        self.gradersId = [NSString stringWithFormat:@"%@",[[self.graderArr objectAtIndex:indexPath.row] objectForKey:@"gradersid"]];
        self.editionType = [NSString stringWithFormat:@"%@",[[self.editionArr objectAtIndex:selectedEditionIndex] objectForKey:@"editiontypeid"]];
        
        self.gradersName = [[self.graderArr objectAtIndex:indexPath.row] objectForKey:@"gradername"];
        self.editionName = [[self.editionArr objectAtIndex:selectedEditionIndex] objectForKey:@"editiontypename"];
        NSString *subStr = [NSString stringWithFormat:@"%@ · %@",[[self.editionArr objectAtIndex:selectedEditionIndex] objectForKey:@"editiontypename"],[[self.graderArr objectAtIndex:indexPath.row] objectForKey:@"gradername"]];
        [self.subjectBtn setTitle:subStr forState:(UIControlStateNormal)];
        
        [self searchRequest:self.snSearch.text];
        
        [self hideControl];
        
    }else if (tableView == self.resultTable) {
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        SN_NewspaperModel *paperModel = [self.resultArr objectAtIndex:indexPath.row];
        
        if (self.searchType == 0) {
            
            SN_NewspaperInfoViewController *vc = [[SN_NewspaperInfoViewController alloc]init];
            vc.paperModel = paperModel;
            
            [self.navigationController pushViewController:vc animated:YES];
            
        }else {
            
            SN_Question_ResolveController *vc = [[SN_Question_ResolveController alloc]init];
            vc.model = paperModel;
            vc.newsId = [NSString stringWithFormat:@"%ld",paperModel.newid];
            
            [self.navigationController pushViewController:vc animated:YES];
            
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    [self.snSearch resignFirstResponder];
}

#pragma mark - Get

- (UITableView *)resultTable {
    
    if (_resultTable == nil) {
        
        _resultTable = [[UITableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight- SafeAreaBottomHeight) style:(UITableViewStylePlain)];
        _resultTable.delegate = self;
        _resultTable.dataSource = self;
        _resultTable.rowHeight = 98;
        _resultTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _resultTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self searchRequest:self.snSearch.text];
        }];
        _resultTable.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self loadMoreResult:self.snSearch.text];
        }];
    }
    return _resultTable;
}

- (UIControl *)control {
    
    if (_control == nil) {
        
        _control = [[UIControl alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight)];
        _control.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"control_bg"]];
        
        [_control addTarget:self action:@selector(hideControl) forControlEvents:UIControlEventTouchUpInside];
    }
    return _control;
}

- (UITableView *) sel_grader {
    
    if (_sel_grader==nil) {
        
        _sel_grader =[[UITableView alloc]initWithFrame:CGRectMake(SCREENWIDTH/2, 0, SCREENWIDTH/2, 360) style:UITableViewStylePlain];
        _sel_grader.delegate=self;
        _sel_grader.dataSource=self;
        _sel_grader.scrollEnabled = NO;
        _sel_grader.separatorStyle= UITableViewCellSeparatorStyleNone;
        _sel_grader.rowHeight = 40.0;
        
    }
    
    return _sel_grader;
}


- (UITableView *) sel_edition {
    
    if (_sel_edition==nil) {
        
        _sel_edition =[[UITableView alloc]initWithFrame:CGRectMake(0,0, SCREENWIDTH/2, 360) style:UITableViewStylePlain];
        _sel_edition.delegate=self;
        _sel_edition.dataSource=self;
        _sel_edition.scrollEnabled = NO;
        _sel_edition.rowHeight = 40.0;
        _sel_edition.separatorStyle= UITableViewCellSeparatorStyleNone;
        _sel_edition.backgroundColor=[UIColor colorWithHexString:@"f4f5f7"];
    }
    
    return _sel_edition;
}

@end
